package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.view.View;

import com.aries.ui.view.radius.RadiusTextView;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseFragment;
import com.chexiehui.jc.event.ChooseHistoryTagEvent;
import com.chexiehui.jc.event.SearchHistoryEvent;
import com.chexiehui.jc.model.SearchHistory;
import com.chexiehui.jc.realm.SearchHistoryDao;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.nex3z.flowlayout.FlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;

public class SearchHomeFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.fl_history_tip)
    FlowLayout flHistoryTip;
    @BindView(R.id.nsgv_quick_gride)
    NonSlidingGridView nsgvQuickGride;

    public static SearchHomeFragment getInstance() {
        SearchHomeFragment fragment = new SearchHomeFragment();
        return fragment;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_search_home;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        changeHistoryTip();
    }

    private void changeHistoryTip(){
        flHistoryTip.removeAllViews();
        List<SearchHistory> historyList = AppApplication.getInstances().getSearchHistoryDao()
                .queryBuilder().limit(10).orderDesc(SearchHistoryDao.Properties.CreateTime).list();
        for (int i = 0; i < historyList.size(); i++) {
            RadiusTextView radiusTextView = (RadiusTextView) View.inflate(mActivity, R.layout.item_only_search_tip, null);
            radiusTextView.setTag(historyList.get(i));
            radiusTextView.setText(historyList.get(i).getName());
            radiusTextView.setOnClickListener(this);
            flHistoryTip.addView(radiusTextView);
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getTag() != null){
            SearchHistory history = (SearchHistory) v.getTag();
            EventBus.getDefault().post(new ChooseHistoryTagEvent(history.getName()));
        }
    }

    @Subscribe
    public void onSearchHistoryEvent(SearchHistoryEvent event){
        changeHistoryTip();
    }
}
